﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using EnvDTE;

namespace Blader.ActionHandler
{
    public class SqlOpenHandler : AbstractActionHandler
    {
        [DllImport("shell32.dll")]
        public extern static IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        public SqlOpenHandler(HandlerContext hanlerContext)
            : base(hanlerContext)
        {
        }

        public override bool Execute()
        {
            if (hanlerContext.ApplicationObject.ActiveDocument != null)
            {
                TextSelection textSelection = (TextSelection)hanlerContext.ApplicationObject.ActiveDocument.Selection;
                if (!textSelection.IsEmpty)
                {
                    OpenSql(textSelection.Text);
                    return true;
                }
            }
            return false;
        }

        private void OpenSql(string fileName)
        {
            if (hanlerContext.ApplicationObject.Solution != null)
            {
                FileInfo fileInfo = new FileInfo(hanlerContext.ApplicationObject.Solution.FileName);
                DirectoryInfo[] dataBaseDirectoty = fileInfo.Directory.GetDirectories("Database");

                foreach (DirectoryInfo directoryInfo in dataBaseDirectoty)
                {
                    FileInfo[] sqlFiles = directoryInfo.GetFiles(fileName + ".sql", SearchOption.AllDirectories);
                    if (sqlFiles.Length > 0)
                    {
                        ShellExecute(IntPtr.Zero, "open", sqlFiles[0].FullName, null, null, 3);
                    }
                    else
                    {
                        MessageBox.Show("Files not found!");
                    }
                }
            }
        }

    }
}
